package godlike.tech.websocket1.config;

import godlike.tech.websocket1.interceptor.HttpHandShakeInterceptor;
import godlike.tech.websocket1.interceptor.InboundChannelInterceptor;
import godlike.tech.websocket1.interceptor.OutboundChannelInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration  //注册为 Spring 配置类
/*
 * 开启使用STOMP协议来传输基于代理（message broker）的消息
 * 启用后控制器支持@MessgeMapping注解
 */
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {


    //注册STOMP协议节点并映射url
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注册一个 /websocket 的 websocket 节点
        registry.addEndpoint("/websocket")
                // 添加 websocket握手拦截器
                .addInterceptors(new HttpHandShakeInterceptor())

                // 设置允许可跨域的域名
                .setAllowedOrigins("*")

                // 指定使用SockJS协议
                .withSockJS();
    }

    /**
     * 定义一些消息连接规范（也可不设置）
     *
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //设置客户端接收消息地址的前缀（可不设置）
        registry.enableSimpleBroker(
                "/topic",   //广播消息前缀
                "/queue"    //点对点消息前缀
        );
        //设置客户端接收点对点消息地址的前缀，默认为 /user
        registry.setUserDestinationPrefix("/user");
        //设置客户端向服务器发送消息的地址前缀（可不设置）
        registry.setApplicationDestinationPrefixes("/app");
    }

    //配置客户端进入通道
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new InboundChannelInterceptor());
    }

    //配置客户端退出通道
    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.interceptors(new OutboundChannelInterceptor());
    }


}